package com.example.icongyou;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.icongyou.api.TeacherCourseApi;
import com.example.icongyou.api.CourseApi;
import com.example.icongyou.bean.TeacherCourse;
import com.example.icongyou.bean.Course;
import com.example.icongyou.bean.ApiResponse;
import com.example.icongyou.manager.KgApiManager;
import com.example.icongyou.retrofit.RetrofitClient;
import com.example.icongyou.utils.SessionManager;
import com.google.android.material.card.MaterialCardView;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CourseCenterFragment extends Fragment {
    private static final String TAG = "CourseCenterFragment";
    private static final int COURSE_IMAGE_HEIGHT_DP = 150;

    private LinearLayout coursesContainer;
    private TextView stateText;
    private SessionManager sessionManager;
    private Map<String, Course> courseDetailsMap = new HashMap<>();
    private LayoutInflater layoutInflater;
    private KgApiManager kgApiManager;
    private ExecutorService executorService;
    private Handler mainHandler;

    public CourseCenterFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        layoutInflater = inflater;
        kgApiManager = new KgApiManager();
        executorService = Executors.newFixedThreadPool(3); // 创建线程池用于图片加载
        mainHandler = new Handler(Looper.getMainLooper()); // 主线程Handler
        return inflater.inflate(R.layout.fragment_course_center, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "onViewCreated");

        try {
            sessionManager = new SessionManager(requireContext());
            initViews(view);

            if (!sessionManager.isLoggedIn()) {
                showState("请先登录");
                Toast.makeText(getContext(), "未检测到登录状态", Toast.LENGTH_LONG).show();
                return;
            }

            loadTeacherCourses();
        } catch (Exception e) {
            Log.e(TAG, "初始化失败", e);
            showState("初始化失败");
        }
    }

    private void initViews(View view) {
        coursesContainer = view.findViewById(R.id.courses_container);
        stateText = view.findViewById(R.id.state_text);

        Log.d(TAG, "初始化视图 - 课程容器: " + (coursesContainer != null));
        Log.d(TAG, "初始化视图 - 状态文本: " + (stateText != null));
    }

    private void loadTeacherCourses() {
        String teacherId = sessionManager.getTeacherId();
        Log.d(TAG, "加载教师课程 - 教师ID: " + teacherId);

        if (teacherId == null || teacherId.isEmpty()) {
            showState("未获取到教师ID，请重新登录");
            return;
        }

        showState("课程加载中...");

        try {
            TeacherCourseApi api = RetrofitClient.getTeacherCourseApi();
            Call<List<TeacherCourse>> call = api.getCoursesByTeacher(teacherId);

            call.enqueue(new Callback<List<TeacherCourse>>() {
                @Override
                public void onResponse(Call<List<TeacherCourse>> call, Response<List<TeacherCourse>> response) {
                    Log.d(TAG, "请求响应 - 状态码: " + response.code());

                    if (response.isSuccessful() && response.body() != null) {
                        List<TeacherCourse> courses = response.body();
                        Log.d(TAG, "获取课程数量: " + courses.size());
                        loadCourseDetails(courses);
                    } else {
                        Log.w(TAG, "获取课程失败，响应体为空");
                        showState("暂无课程数据");
                    }
                }

                @Override
                public void onFailure(Call<List<TeacherCourse>> call, Throwable t) {
                    Log.e(TAG, "网络请求失败", t);
                    showState("网络连接失败");
                    Toast.makeText(getContext(), "请检查网络连接", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "加载课程异常", e);
            showState("加载异常");
            Toast.makeText(getContext(), "加载异常: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void loadCourseDetails(List<TeacherCourse> teacherCourses) {
        if (teacherCourses == null || teacherCourses.isEmpty()) {
            showState("暂无课程");
            return;
        }

        courseDetailsMap.clear();
        final int[] loadedCount = {0};
        final int totalCount = teacherCourses.size();

        for (TeacherCourse teacherCourse : teacherCourses) {
            String courseId = teacherCourse.getCourseId();
            loadSingleCourseDetail(courseId, loadedCount, totalCount, teacherCourses);
        }
    }

    private void loadSingleCourseDetail(String courseId, int[] loadedCount,
                                        int totalCount, List<TeacherCourse> teacherCourses) {
        try {
            CourseApi courseApi = RetrofitClient.getCourseApi();
            Call<Course> courseCall = courseApi.getCourseById(courseId);

            courseCall.enqueue(new Callback<Course>() {
                @Override
                public void onResponse(Call<Course> call, Response<Course> response) {
                    handleCourseDetailResponse(courseId, response);
                    checkAndDisplayCourses(loadedCount, totalCount, teacherCourses);
                }

                @Override
                public void onFailure(Call<Course> call, Throwable t) {
                    handleCourseDetailFailure(courseId, t);
                    checkAndDisplayCourses(loadedCount, totalCount, teacherCourses);
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "加载课程详情异常: " + courseId, e);
            checkAndDisplayCourses(loadedCount, totalCount, teacherCourses);
        }
    }

    private void handleCourseDetailResponse(String courseId, Response<Course> response) {
        if (response.isSuccessful() && response.body() != null) {
            Course course = response.body();
            courseDetailsMap.put(courseId, course);
            Log.d(TAG, "加载课程详情成功: " + course.getCourseName() + ", PNG: " + course.getPng());
        } else {
            // 假设 Course 构造函数需要7个参数
            Course defaultCourse = new Course(
                    courseId,                    // course_id
                    "课程-" + courseId,          // course_name
                    "",                         // description
                    "2024-1",                   // semester_id (需要提供)
                    1,                          // teacher_id (需要提供)
                    "10",                       // total_lessons (需要提供)
                    ""                          // png (需要提供)
            );
            courseDetailsMap.put(courseId, defaultCourse);
            Log.w(TAG, "获取课程详情失败: " + courseId);
        }
    }

    private void handleCourseDetailFailure(String courseId, Throwable t) {
        // 假设 Course 构造函数需要7个参数
        Course defaultCourse = new Course(
                courseId,                    // course_id
                "课程-" + courseId,          // course_name
                "",                         // description
                "2024-1",                   // semester_id (需要提供)
                1,                          // teacher_id (需要提供)
                "10",                       // total_lessons (需要提供)
                ""                          // png (需要提供)
        );
        courseDetailsMap.put(courseId, defaultCourse);
        Log.e(TAG, "课程详情请求失败: " + courseId, t);
    }

    private void checkAndDisplayCourses(int[] loadedCount, int totalCount, List<TeacherCourse> teacherCourses) {
        loadedCount[0]++;
        if (loadedCount[0] == totalCount) {
            displayCourses(teacherCourses);
        }
    }

    private void displayCourses(List<TeacherCourse> teacherCourses) {
        if (coursesContainer == null) {
            Log.e(TAG, "课程容器为空");
            return;
        }

        coursesContainer.removeAllViews();

        if (teacherCourses.isEmpty()) {
            Log.d(TAG, "没有课程数据");
            showState("暂无课程");
            return;
        }

        Log.d(TAG, "显示课程数量: " + teacherCourses.size());
        stateText.setVisibility(View.GONE);
        coursesContainer.setVisibility(View.VISIBLE);

        for (TeacherCourse teacherCourse : teacherCourses) {
            try {
                View courseCard = createCourseCard(teacherCourse);
                if (courseCard != null) {
                    coursesContainer.addView(courseCard);
                }
            } catch (Exception e) {
                Log.e(TAG, "创建课程卡片失败: " + teacherCourse.getCourseId(), e);
            }
        }
    }

    private View createCourseCard(TeacherCourse teacherCourse) {
        // 从模板加载卡片视图
        MaterialCardView card = (MaterialCardView) layoutInflater.inflate(
                R.layout.item_course_card_teacher, coursesContainer, false);

        // 获取控件引用
        ImageView courseImage = card.findViewById(R.id.course_image);
        TextView courseName = card.findViewById(R.id.course_name);
        TextView courseDesc = card.findViewById(R.id.course_description);
        TextView courseId = card.findViewById(R.id.course_id);

        // 设置数据
        String courseIdStr = teacherCourse.getCourseId();
        Course course = courseDetailsMap.get(courseIdStr);

        courseName.setText(getCourseName(course, courseIdStr));
        courseDesc.setText(getCourseDescription(course));
        courseId.setText("课程ID: " + courseIdStr);

        // 加载课程图片
        loadCourseImage(course, courseImage);

        // 设置点击事件
        card.setOnClickListener(v -> {
            String name = getCourseName(course, courseIdStr);
            Toast.makeText(getContext(), "点击课程: " + name, Toast.LENGTH_SHORT).show();
        });

        return card;
    }

    private void loadCourseImage(Course course, ImageView imageView) {
        if (course == null || course.getPng() == null || course.getPng().isEmpty()) {
            Log.d(TAG, "课程图片为空，使用默认图片");
            setDefaultImage(imageView);
            return;
        }

        String pngFileName = course.getPng();
        Log.d(TAG, "加载课程图片: " + pngFileName);

        // 使用KgApiManager获取教材URL来加载图片
        kgApiManager.getTextBookUrl(pngFileName, new KgApiManager.ApiCallback<ApiResponse<String>>() {
            @Override
            public void onSuccess(ApiResponse<String> response) {
                if (response != null && response.isSuccess()) {
                    String imageUrl = response.getMsg();
                    Log.d(TAG, "获取图片URL成功: " + imageUrl);

                    // 使用原生方式加载网络图片
                    loadImageFromUrl(imageUrl, imageView);
                } else {
                    String errorMsg = response != null ? response.getMsg() : "null";
                    Log.w(TAG, "获取图片URL失败: " + errorMsg);
                    // 设置默认图片
                    setDefaultImage(imageView);
                }
            }

            @Override
            public void onError(String errorMessage) {
                Log.e(TAG, "获取图片URL错误: " + errorMessage);
                // 设置默认图片
                setDefaultImage(imageView);
            }
        });
    }

    /**
     * 使用原生方式从URL加载图片
     */
    private void loadImageFromUrl(String imageUrl, ImageView imageView) {
        if (imageUrl == null || imageUrl.isEmpty()) {
            setDefaultImage(imageView);
            return;
        }

        executorService.execute(() -> {
            try {
                URL url = new URL(imageUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();

                InputStream input = connection.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(input);

                // 回到主线程更新UI
                mainHandler.post(() -> {
                    if (bitmap != null) {
                        imageView.setImageBitmap(bitmap);
                        Log.d(TAG, "图片加载成功");
                    } else {
                        Log.w(TAG, "图片解码失败");
                        setDefaultImage(imageView);
                    }
                });

                input.close();
                connection.disconnect();

            } catch (Exception e) {
                Log.e(TAG, "图片加载失败: " + e.getMessage());
                mainHandler.post(() -> setDefaultImage(imageView));
            }
        });
    }

    /**
     * 设置默认图片
     */
    private void setDefaultImage(ImageView imageView) {
        try {
            // 使用Android原生方式设置默认图片
            // 这里可以设置一个本地的默认图片资源
            // imageView.setImageResource(R.drawable.default_course_image);

            // 或者设置一个默认的颜色背景
            imageView.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
            imageView.setScaleType(ImageView.ScaleType.CENTER);

            // 可以在图片中央显示一个文本提示
            // 如果需要显示文本，可以使用其他View组合来实现
        } catch (Exception e) {
            Log.e(TAG, "设置默认图片失败", e);
        }
    }

    private String getCourseName(Course course, String courseId) {
        if (course != null && course.getCourseName() != null) {
            return course.getCourseName();
        }
        return "课程-" + courseId;
    }

    private String getCourseDescription(Course course) {
        if (course != null && course.getDescription() != null) {
            return course.getDescription();
        }
        return "暂无描述";
    }

    private int dpToPx(int dp) {
        return Math.round(dp * getResources().getDisplayMetrics().density);
    }

    private void showState(String message) {
        if (stateText != null) {
            stateText.setText(message);
            stateText.setVisibility(View.VISIBLE);
        }
        if (coursesContainer != null) {
            coursesContainer.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 清理资源
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
        }
        if (mainHandler != null) {
            mainHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }
}